package cn.com.flever.component;

import cn.com.flever.entity.PomModel;
import cn.com.flever.utils.GenerateUtils;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import javax.swing.*;
import java.awt.event.*;
import java.io.File;
import java.util.List;

/**
 * 代码生成器界面
 */
public class GenerateCodeDialog extends JDialog {

    private JPanel contentPane;

    private JButton buttonOK;//生成按钮

    private JTextField textField1;//生成目录输入框

    private JButton selectButton;//生成目录选择按钮

    private JTextField textField2;//pdm文件目录输入框

    private JButton selectButton1;//dpm文件目录选择按钮

    private Project project;//当前idea的project

    private String path = "";//代码生成路径

    private String pmdPath = "";//pdm文件路径

    private String packagePath = "";//生成代码在project中的包路径

    private VirtualFile currentFile;//当前选择的文件目录

    /**
     * 代码生成器界面构造器
     *
     * @param project      当前idea所在project
     * @param generateFolder 当前选择的文件目录
     */
    public GenerateCodeDialog(Project project, VirtualFile generateFolder) {
        //init
        this.project = project;
        String generatePath=null;
        if(generateFolder!=null&&generateFolder.isDirectory())
        {
            currentFile=generateFolder;
            generatePath=currentFile.getPath();
        }
        if (!StringUtils.isEmpty(generatePath)) {
            //目录不为空则记录入输入框
            path = generatePath;
            //目录格式化
            packagePath = path.replace(project.getBasePath() + "/src/main/java/", "");
            packagePath = packagePath.replace("/", ".");
        }
        //设置界面
        setContentPane(contentPane);
        setModal(true);
        getRootPane().setDefaultButton(buttonOK);
        setTitle("Generator Code");
        textField1.setText(path);
        textField2.setText(pmdPath);

        //generate按钮生成代码监听
        buttonOK.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onOK();
            }
        });

        //生成目录选择监听
        selectButton.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //初始化fileChoose，并获得选择的目录
                String tmpPath = selectPath(project, false, true,currentFile);
                textField1.setText(tmpPath);
                path = tmpPath;
                //参数格式化
                packagePath = tmpPath.replace(project.getBasePath() + "/src/main/java/", "");
                packagePath = packagePath.replace("/", ".");
            }
        });

        //pdm目录选择监听
        selectButton1.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //初始化fileChoose，并获得选择的目录
                String tmpPath = selectPath(project, true, false,null);
                textField2.setText(tmpPath);
                pmdPath = tmpPath;

            }
        });

        // X关闭按钮事件
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

        // 键盘Esc关闭事件
        contentPane.registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    }

    /**
     * generate按钮事件
     */
    private void onOK() {
        //解析pom
        PomModel pom = getPom(project);
        //生成代码
        GenerateUtils.getFullModel(path, packagePath, pmdPath, pom);
        dispose();
    }

    private void onCancel() {
        dispose();
    }


    /**
     * 唤出fileChoose
     *
     * @param project       当前所在项目
     * @param chooseFile    是否选择文件
     * @param chooseFolder  是否选择目录
     * @param currentFolder 当前鼠标选择的目录
     * @return
     */
    public static String selectPath(Project project, boolean chooseFile, boolean chooseFolder, VirtualFile currentFolder) {
        //生成fileChoose
        FileChooserDescriptor fileChooserDescriptor = new FileChooserDescriptor(chooseFile, chooseFolder, false, false, false, false);
        //设置当前目录
        VirtualFile selectFile = project.getBaseDir();
        //获取选择的文件
        VirtualFile file = FileChooser.chooseFile(fileChooserDescriptor, project, currentFolder == null ? selectFile : currentFolder);
        return file.getPath();
    }

    /**
     * 解析项目pom文件
     *
     * @param project
     * @return
     */
    public PomModel getPom(Project project) {
        //获取pom文件
        String path = project.getBasePath();
        File pom = new File(path + File.separator + "pom.xml");
        if (!pom.exists()) {
            //不存在，抛出提示
            Messages.showErrorDialog(
                    "Can not find pom.xml",
                    "pom.xml error");
            onCancel();
        } else {
            try {
                SAXReader reader = new SAXReader();
                Document document = reader.read(pom);
                Element root = document.getRootElement();
                //找到每一个Column定义，添加或修改注释
                String name=document.getRootElement().element("name").getText();
                String artifactId=document.getRootElement().element("artifactId").getText();
                PomModel pomModel =new PomModel();
                pomModel.setArtifactId(artifactId);
                pomModel.setName(name);
                if (StringUtils.isEmpty(pomModel.getArtifactId()) || StringUtils.isEmpty(pomModel.getName())) {
                    Messages.showErrorDialog(
                            project,
                            "Can not find artifactId or name in pom.xml",
                            "pom.xml parse error");
                    onCancel();
                }
                return pomModel;
            } catch (Exception e) {
                e.printStackTrace();
                Messages.showErrorDialog(
                        project,
                        "Can not find artifactId or name in pom.xml",
                        "pom.xml parse error");
                onCancel();
            }
        }
        return null;
    }

    /**
     * 设置当前目录
     * @param currentFile
     */
    public void setCurrentFile(VirtualFile currentFile) {
        this.currentFile = currentFile;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public void setPackagePath(String packagePath) {
        this.packagePath = packagePath;
    }

    public void setGeneratePath(String path) {
        this.textField1.setText(path);
    }
}
